package com.coding.mybatis;

import lombok.AllArgsConstructor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Objects;

/**
 * @ClassName MapperProxy
 * @Author ykx
 * @Date 2023/12/31 18:11
 * @Version 1.0
 */
@AllArgsConstructor
public class MapperProxy implements InvocationHandler {
    /**
     * session
     */
    private SqlSession session;

    /**
     * mapperInterface接口
     */
    private Class<?> mapperInterface;

    /**
     * 配置configuration
     */
    private Configuration configuration;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String name = method.getName();
        String statementId = mapperInterface.getName() + "." + name;

        MappedStatement mappedStatement = configuration.getStatementMap().get(statementId);

        if (Objects.nonNull(mappedStatement) && Objects.equals(mappedStatement.getId(), name)) {
            if (Collection.class.isAssignableFrom(method.getReturnType())) {
                return session.selectList(statementId, args);
            } else {
                return session.selectOne(statementId, args);
            }
        }

        return method.invoke(proxy, args);
    }
}
